package com.stenio.fancat.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.stenio.fancat.common.constants.GlobalConstant;

/**
 * 保存请求参数，统一处理请求信息<br>
 * 通过@Configuration注解将filter类加入过滤链<br>
 * 此类与 @see WebConfig,RequestInterceptor,ThreadCache 配合使用
 */
// @Configuration
// @WebFilter(urlPatterns = "/*", filterName = "InterfaceFilter")
public class InterfaceFilter implements Filter {

	private static Logger logger = LoggerFactory.getLogger(InterfaceFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		// HttpServletResponse res = (HttpServletResponse) response;
		// logger.info("filer-post请求参数:[params={}]", req);
		try {
			WrappedHttpServletRequest wrappedHttpServletRequest = new WrappedHttpServletRequest(req);
			String contentType = req.getContentType();
			if (contentType != null) {
				contentType = contentType.toLowerCase();
			}
			if ("POST".equals(req.getMethod().toUpperCase())
					&& (GlobalConstant.PLATFORM_RESPONSE_CONTENTTYPE_JSON.equals(contentType)
							|| GlobalConstant.CONTENTTYPE_JSON_UTF_8.equals(contentType))) {
				// 获取请求参数
				String params = wrappedHttpServletRequest.getRequestParams();
				ThreadCache.setPostRequestParams(params);
				// logger.info("filer-post请求参数:[params={}]", params);
			} else {
				// logger.info("非post请求");
			}

			chain.doFilter(wrappedHttpServletRequest, response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	@Override
	public void destroy() {

	}
}